package com.rxnetwork.sample.test;

import android.annotation.TargetApi;
import android.os.Build;
import android.webkit.MimeTypeMap;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.gzsll.jsbridge.WVJBWebView;
import com.gzsll.jsbridge.WVJBWebViewClient;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;

/**
 * Created by Administrator on 2017/7/10.
 */

public class CustomWebViewClient extends WVJBWebViewClient {

    WVJBWebView mWebView;

    public CustomWebViewClient(WVJBWebView webView) {
        super(webView);
        mWebView = webView;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        //  do your work here
        // ...
        return super.shouldOverrideUrlLoading(view, url);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        WebResourceResponse response;
        response = super.shouldInterceptRequest(view, url);
        response = getWebResourceResponse(url, response);
        return response;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        WebResourceResponse response;
        response = super.shouldInterceptRequest(view, request);
        response = getWebResourceResponse(request.getUrl().getScheme() + "://" + request.getUrl().getHost() + request.getUrl().getPath(), response);
        return response;
    }

    private WebResourceResponse getWebResourceResponse(String url, WebResourceResponse response) {
        try {
            InputStream inputStream = null;
            if (url.contains(".css") || url.contains(".js")) {
                String[] strArr = url.split("/");
                String fileName = strArr[strArr.length - 1];
                inputStream = mWebView.getContext().getAssets().open(fileName);
                if (inputStream != null) {
                    if (url.contains(".css")) {
                        response = new WebResourceResponse(getMimeType(fileName), "UTF-8", inputStream);
                    }
                    if (url.contains(".js")) {
                        response = new WebResourceResponse(getMimeType(fileName), "UTF-8", inputStream);
                    }
                }
            } else if (isImageType(url)) {
                File file = Glide.with(mWebView.getContext())
                        .load(url)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
                inputStream = getFileStream(file);
                if (inputStream != null) {
                    response = new WebResourceResponse(getMimeType(file.getName()), "UTF-8", inputStream);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return response;
    }

    private InputStream getFileStream(File file) {
        ByteArrayInputStream tInputStringStream = null;
        if (file != null) {
            tInputStringStream = new ByteArrayInputStream(getBytes(file));
        }
        return tInputStringStream;
    }

    private byte[] getBytes(File file) {
        if (file == null) {
            return null;
        }
        try {
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) != -1)
                out.write(b, 0, len);
            in.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获得获取文件的扩展名
     *
     * @param name
     * @return
     */
    private static String getExtension(String name) {
        String suffix = "";
        final int idx = name.lastIndexOf(".");
        if (idx > 0) {
            suffix = name.substring(idx + 1);
        }
        return suffix;
    }

    /**
     * 通过扩展名获取MIME类型
     *
     * @param fileName
     * @return
     */
    private static String getMimeType(String fileName) {
        String extension = getExtension(fileName);
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }

    private boolean isImageType(String url) {
//        bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw
        if (url.contains(".bmp") || url.contains(".jpg") || url.contains(".png") || url.contains(".tiff") || url.contains(".gif")
                || url.contains(".pcx") || url.contains(".tga") || url.contains(".exif") || url.contains(".fpx") || url.contains(".svg")
                || url.contains(".psd") || url.contains(".cdr") || url.contains(".pcd") || url.contains(".dxf") || url.contains(".ufo")
                || url.contains(".eps") || url.contains(".ai") || url.contains(".raw")) {
            return true;
        }
        return false;
    }
}
